package com.movitech.mobile.ddzy.modules.bpm.bizservice.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.gson.Gson;
import com.movitech.mobile.cz.base.common.license.LicenseUtil;
import com.movitech.mobile.cz.base.common.util.CommonConstants;
import com.movitech.mobile.cz.base.common.util.IdGenUtils;
import com.movitech.mobile.cz.base.common.util.StringUtils;
import com.movitech.mobile.cz.base.modules.config.AbutmentSubTypeEnum;
import com.movitech.mobile.cz.base.modules.config.ActionTypeEnum;
import com.movitech.mobile.cz.base.purchase.bizservice.WorkFlowService;
import com.movitech.mobile.cz.base.supplier.bizservice.SSuppliersEvaluationService;
import com.movitech.mobile.cz.base.supplier.bizservice.SSuppliersWorkFlowService;
import com.movitech.mobile.cz.base.supplier.bizvo.PurchaseMbsCallBackVO;
import com.movitech.mobile.cz.base.supplier.bizvo.SupplierRankApprovalResultVo;
import com.movitech.mobile.cz.base.supplier.bizvo.SuppliersAuditRequestVO;
import com.movitech.mobile.ddzy.bpm.entity.SBpm;
import com.movitech.mobile.ddzy.bpm.entity.SBpmCallback;
import com.movitech.mobile.ddzy.bpm.service.SBpmCallbackService;
import com.movitech.mobile.ddzy.bpm.service.SBpmService;
import com.movitech.mobile.ddzy.modules.bpm.bizservice.MbsBpmCallBackService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service(value = "mbsBpmCallBackService")
public class MbsBpmCallBackServiceImpl implements MbsBpmCallBackService {

    @Autowired
    @Qualifier("sBpmService")
    private SBpmService sBpmService;

    @Autowired
    @Qualifier("sBpmCallbackService")
    private SBpmCallbackService sBpmCallbackService;

    @Autowired
    @Qualifier("sSuppliersWorkFlowService")
    private SSuppliersWorkFlowService sSuppliersWorkFlowService;
    @Autowired
    private SSuppliersEvaluationService sSuppliersEvaluationService;

    @Autowired
    @Qualifier("workFlowService")
    private WorkFlowService workFlowService;

    @Override
    public SBpmCallback saveBpmCallBack(Map<String, String> requestBody) {
        LicenseUtil.INSTANCE.validate();
        String resultBody = JSONObject.toJSONString(requestBody);
        System.out.println(String.format("----RequestBody-->%s", resultBody));

        //状态: 1归档2打回 3作废(驳回到开始)
        String bpmStatus = requestBody.get("evenType");
        String bpmId = requestBody.get("BPMId");
        if(StringUtils.isEmpty(bpmId)){
            bpmId = requestBody.get("instanceId");
        }

        SBpmCallback sBpmCallback = new SBpmCallback();
        sBpmCallback.setId(IdGenUtils.uuid());
        sBpmCallback.setBaseFeilds(null, null, CommonConstants.NO_INTEGER, true);
        sBpmCallback.setFormId(bpmId);
        sBpmCallback.setCallBackStatus(bpmStatus);
        sBpmCallback.setCallBackResuls(resultBody);

        EntityWrapper<SBpm> wrapper = new EntityWrapper<SBpm>();
        SBpm sBpmEntity = new SBpm();
        sBpmEntity.setWorkFlowId(bpmId);
        wrapper.setEntity(sBpmEntity);
        List<SBpm> lstSBpm = sBpmService.selectList(wrapper);
        SBpm sBpm = lstSBpm.get(0);
        if (lstSBpm != null && lstSBpm.size() > 0) {
            sBpmCallback.setBpmRelatedType(sBpm.getBpmRelatedType());
        }
        sBpmCallbackService.insert(sBpmCallback);
        return sBpmCallback;
    }

    @Override
    public void updateBpmCallBack(SBpmCallback updateCallback) {
        sBpmCallbackService.updateById(updateCallback);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackForClassName = {"RuntimeException", "Exception"})
    @Override
    public boolean mbsBpmCallBack(Map<String, String> requestBody) throws RuntimeException {
        LicenseUtil.INSTANCE.validate();
        boolean isOk = false;
        Gson gson = new Gson();
        try {
            String resultBody = JSONObject.toJSONString(requestBody);
            String bpmStatus = requestBody.get("evenType");
            String bpmId = requestBody.get("BPMId");
            if(StringUtils.isEmpty(bpmId)){
                bpmId = requestBody.get("instanceId");
            }
            if (StringUtils.isNotEmpty(bpmId)) {
                EntityWrapper<SBpm> wrapper = new EntityWrapper<SBpm>();
                SBpm sBpmEntity = new SBpm();
                sBpmEntity.setWorkFlowId(bpmId);
                wrapper.setEntity(sBpmEntity);
                List<SBpm> lstSBpm = sBpmService.selectList(wrapper);
                if (!CollectionUtils.isEmpty(lstSBpm)) {
                    SBpm entity = lstSBpm.get(0);

                    if (entity.getAbutmentType() != null) {
                        if (entity.getAbutmentType() == CommonConstants.BPM_ABUTMENT_TYPE_SUPPLIER) {
                            if (entity.getAbutmentSubType() != null && AbutmentSubTypeEnum.RANK_APPROVE.getCode() == entity.getAbutmentSubType()) {//供应商定级审批
                                SupplierRankApprovalResultVo supplierRankApprovalResultVo = new SupplierRankApprovalResultVo();
                                supplierRankApprovalResultVo.setId(entity.getRelatedId());
                                supplierRankApprovalResultVo.setAgreeFlag(StringUtils.equalsIgnoreCase(bpmStatus, "1") ? 2 : 1);
                                sSuppliersEvaluationService.approvalSupplierRankFinal(supplierRankApprovalResultVo);
                            } else {
                                if (StringUtils.equalsIgnoreCase(bpmStatus, "2")) {
                                    // 状态: 1归档2打回 3作废(驳回到开始)
                                    //审批未通过，生成流程被驳回待办，后续操作交由用户处理选择是作废流程还是提交审批（若用户选择作废流程，此时认为流程审批不通过，进而更新业务表状态，若选择提交审批，则将原流程ID作为参数提交，在原流程基础上继续审批）
                                    sBpmService.bpmRejected(entity);
                                    return true;
                                }
                                /////供方入库
                                String abutmentDetailUrl = "";
                                SuppliersAuditRequestVO suppliersAuditRequestVo = new SuppliersAuditRequestVO();
                                suppliersAuditRequestVo.setId(entity.getRelatedId());
                                suppliersAuditRequestVo.setRcRelatedId(entity.getSubRelatedId());
                                suppliersAuditRequestVo.setComments("");
                                // 审核不通过
                                if (!StringUtils.equalsIgnoreCase(bpmStatus, "1")) {
                                    suppliersAuditRequestVo.setActionType(ActionTypeEnum.UNPASS_AUDIT.getCode());
                                } else {//审核通过
                                    suppliersAuditRequestVo.setActionType(ActionTypeEnum.PASSS_AUDIT.getCode());
                                }
                                suppliersAuditRequestVo.setAbutmentType(entity.getAbutmentType());
                                suppliersAuditRequestVo.setAbutmentSubType(entity.getAbutmentSubType());
                                suppliersAuditRequestVo.setAbutmentDetailUrl(abutmentDetailUrl);
                                sSuppliersWorkFlowService.doSupplierStorageProcess(suppliersAuditRequestVo);
                            }
                        } else if (entity.getAbutmentType() == CommonConstants.BPM_ABUTMENT_TYPE_PURCHASE) {
                            ///mbs的流程链接
                           /* String abutmentDetailUrl = "";
                            if (StringUtils.isNotEmpty(entity.getAbutmentResult())) {
                                BpmFlowReturn bpmFlowReturn = gson.fromJson(entity.getAbutmentResult(), new TypeToken<BpmFlowReturn>() {
                                }.getType());
                                if (bpmFlowReturn != null) {
                                    abutmentDetailUrl = bpmFlowReturn.getUrl();
                                }
                            }*/

                            ////
                            PurchaseMbsCallBackVO purchaseMbsCallBackVO = new PurchaseMbsCallBackVO();
                            purchaseMbsCallBackVO.setFlowFormId(entity.getRelatedId());
                            purchaseMbsCallBackVO.setRcRelatedId(entity.getSubRelatedId());
                            purchaseMbsCallBackVO.setComments("");

                            if (!StringUtils.equalsIgnoreCase(bpmStatus, "1")) {//审核不通过
                                purchaseMbsCallBackVO.setAgreeFlag(CommonConstants.NO_AGREE_FLAG);

                            } else {//审核通过
                                purchaseMbsCallBackVO.setAgreeFlag(CommonConstants.AGREE_FLAG);
                            }

                            purchaseMbsCallBackVO.setAbutmentSubType(entity.getAbutmentSubType());
//                            purchaseMbsCallBackVO.setAbutmentDetailUrl(abutmentDetailUrl);
                            workFlowService.purchaseMbsCallBack(purchaseMbsCallBackVO);
                        }
                    }
                }
                isOk = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
        return isOk;
    }

}
